package com.android.myipc.soket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * Created by Android Studio.
 * User: pengym
 * Date: 2020/11/12
 * Time: 14:53
 * Name: 作用类：服务端设计
 */
public class TCPService extends Service {
    private boolean mIsServiceDestoryed = false;
    private String[] mDefindMessages = new String[]{
            "你好啊，哈哈",
            "请问你叫什么名字",
            "今天北京天气不错啊，shy",
            "你知道吗？我是可以和多个人同时聊天的哦",
            " 给你讲个笑话把： 据说爱笑的人运气都不会太差"
    };

    @Override
    public void onCreate() {
        new Thread(new TcpService()).start();
        super.onCreate();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        mIsServiceDestoryed = true;
        super.onDestroy();
    }

    private class TcpService implements Runnable {
        @Override
        public void run() {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8688);
            } catch (IOException e) {
                System.out.println("establish tcp server failed ,port:8688");
                e.printStackTrace();
                return;
            }
            while (!mIsServiceDestoryed) {
                try {
                    //接手客户端请求
                    final Socket chilet = serverSocket.accept();
                    System.out.println("accept");
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                responseClient(chilet);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //接收客户端消息
    private void responseClient(Socket chilet) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(chilet.getInputStream()));
        //发送客户端消息
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(chilet.getOutputStream())), true);
        out.println("欢迎来到聊天室！");
        while (!mIsServiceDestoryed) {
            String str = in.readLine();
            System.out.println("msg from client:" + str);
            if (str == null) {
                break;
            }
            int i = new Random().nextInt(mDefindMessages.length);
            String msg = mDefindMessages[i];
            out.println(msg);
            System.out.println("send:" + msg);
        }
        System.out.println("chlent quit.");
        //关闭流
        in.close();
        out.close();
        chilet.close();
    }

}
